﻿
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Game.Tools
{
    public class MapData
    {
        // 0：墙  1：路 2：钥匙 3：门 4：入口楼梯 5：宝箱 6 npc 7 敌人 8：出口楼梯
        public String id;
        public int[][] map;
        public static string _BASE_MAPPATH = "map/";

        public static string savePath = "";

        /// <summary>
        /// 保存地图信息（保存状态）
        /// </summary>
        /// <param name="mapData">修改后的地图状态</param>
        /// <returns></returns>
        public bool CreateMapData(MapData mapData)
        {
            if (Directory.Exists(savePath) == false)//如果不存在就创建file文件夹
            {
                DirectoryInfo directoryInfo = new DirectoryInfo(_BASE_MAPPATH);
                directoryInfo.Create();
            }

            //通过线程处理，防止写入时影响游戏进程
            savePath = _BASE_MAPPATH + "map" + mapData.id + ".map";
            Thread mapSaveThread = new Thread(MapDataCreateTool);
            mapSaveThread.Start(mapData);
            return true;
        }
        /// <summary>
        /// 写入新的地图信息
        /// </summary>
        /// <param name="mapData">地图信息（状态）</param>
        public void MapDataCreateTool(object mapData)
        {
            MapData md = (MapData)mapData;
            int[][] newMap = md.map;
            JObject jo = JObject.FromObject(new { originMapData = newMap, mapData = newMap });
            string toJson = jo.ToString();
            
            toJson = StringFormat(toJson);
            Console.WriteLine(toJson);

            //如果文件不存在，则创建；存在则覆盖
            System.IO.File.WriteAllText(savePath, toJson, Encoding.UTF8);
        }

        public string StringFormat(string obj)
        {
            obj = obj.Replace(" ", "");
            obj = obj.Replace("\t", "");
            obj = obj.Replace("\n", "");
            obj = obj.Replace("\r", "");
            return obj;
        }
    }
}
